<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="发起投诉" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable
                      @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

        <el-table v-loading="loading" :data="ordersList">
          <el-table-column label="订单号" align="center" prop="orderNo"/>
          <el-table-column label="订单标题" align="center" prop="orderTitle"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-chat-dot-square"
                         @click="handleComplaint(scope.row)">我要投诉
              </el-button>
        </template>
      </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>
      </el-tab-pane>

      <el-tab-pane label="我的投诉历史" name="second">
        <el-form :model="complaintQueryParams" ref="complaintQueryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="处理状态" prop="status">
            <el-select v-model="complaintQueryParams.status" placeholder="请选择处理状态" clearable>
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleComplaintHistoryQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetComplaintHistoryQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="complaintLoading" :data="complaintHistoryList">
          <el-table-column label="订单号" align="center" prop="orderNo"/>
          <el-table-column label="投诉内容" align="center">
        <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleViewContent(scope.row)"
              >查看详情</el-button>
        </template>
      </el-table-column>
          <el-table-column label="被投诉职位" align="center" prop="position"/>
          <el-table-column label="被投诉人/事" align="center" prop="positionName"/>
          <el-table-column label="处理状态" align="center" prop="status">
        <template slot-scope="scope">
              <span>{{ formatStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
          <el-table-column label="解决方案" align="center">
        <template slot-scope="scope">
          <el-button
                v-if="scope.row.solution"
            size="mini"
            type="text"
                @click="handleViewSolution(scope.row)"
              >查看解决方案</el-button>
              <span v-else>暂无</span>
            </template>
          </el-table-column>
          <el-table-column label="投诉时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>
        <pagination v-show="complaintTotal > 0" :total="complaintTotal" :page.sync="complaintQueryParams.pageNum"
                    :limit.sync="complaintQueryParams.pageSize" @pagination="getComplaintHistory"/>
      </el-tab-pane>
    </el-tabs>

    <!-- 提交投诉对话框 -->
    <el-dialog :title="complaintTitle" :visible.sync="complaintOpen" width="600px" append-to-body>
      <el-form ref="complaintForm" :model="complaintForm" :rules="complaintRules" label-width="120px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="complaintForm.orderNo" placeholder="投诉的订单号" disabled/>
        </el-form-item>
        <el-form-item label="被投诉职位" prop="position">
          <el-checkbox-group v-model="complaintForm.position" @change="handlePositionChange">
            <el-checkbox label="售前"/>
            <el-checkbox label="售中"/>
            <el-checkbox label="售后"/>
            <el-checkbox label="技术"/>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="被投诉人/事" prop="selectedTargetNames">
          <el-checkbox-group v-model="complaintForm.selectedTargetNames" v-if="targetOptions.length > 0">
            <el-checkbox v-for="target in targetOptions" :key="target.id ? (target.id + target.name) : target.name"
                         :label="target.name"/>
          </el-checkbox-group>
          <span v-else>请先选择被投诉职位</span>
        </el-form-item>
        <el-form-item label="投诉内容" prop="content">
          <editor v-model="complaintForm.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="您的联系方式" prop="userContact">
          <el-input v-model="complaintForm.userContact" placeholder="请输入您的手机或QQ，方便我们与您沟通"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitComplaintForm">提 交</el-button>
        <el-button @click="cancelComplaint">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看内容详情对话框 -->
    <el-dialog :title="contentViewTitle" :visible.sync="contentViewOpen" width="700px" append-to-body>
      <div class="complaint-content-view" v-html="currentContentView"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="contentViewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders } from "@/api/dashboard/orders";
import { listComplaint, addComplaint } from "@/api/quick/complaint";
import {
  mapGetters
} from 'vuex'
import Editor from '@/components/Editor';

export default {
  name: "MyComplaint",
  components: { Editor },
  dicts: ['complaint_status'],
  data() {
    return {
      // Tab
      activeName: 'first',
      showSearch: true,

      // 发起投诉 Tab
      loading: true,
      total: 0,
      ordersList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null
      },

      // 投诉历史 Tab
      complaintLoading: false,
      complaintTotal: 0,
      complaintHistoryList: [],
      complaintQueryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null
      },
      // 处理状态字典
      statusOptions: [
        { value: '0', label: '待处理' },
        { value: '1', label: '处理中' },
        { value: '2', label: '已解决' },
        { value: '3', label: '已关闭' },
        { value: '4', label: '已驳回' }
      ],

      // 投诉弹窗
      complaintTitle: "",
      complaintOpen: false,
      complaintForm: {},
      selectedOrder: null, // 存储当前操作的订单行数据
      targetOptions: [], // 动态生成的被投诉人选项
      // 内容详情
      contentViewOpen: false,
      contentViewTitle: "投诉详情",
      currentContentView: "",
      complaintRules: {
        position: [{
          type: 'array',
          required: true,
          message: "请至少选择一个要投诉的职位",
          trigger: "change"
        }],
        selectedTargetNames: [{
          type: 'array',
          required: true,
          message: "请至少选择一个要投诉的人/事",
          trigger: "change"
        }],
        content: [{
          required: true,
          message: "投诉内容不能为空",
          trigger: "blur"
        }],
        userContact: [{
          required: true,
          message: "联系方式不能为空",
          trigger: "blur"
        }],
      },
    };
  },
  computed: {
    ...mapGetters([
      'userId',
      'name',
      'phonenumber' // 假设store中有用户信息
    ])
  },
  created() {
    this.getList();
  },
  methods: {
    formatStatus(status) {
      if (status === null || status === undefined) return "";
      const statusStr = String(status);
      const option = this.statusOptions.find(item => item.value === statusStr);
      return option ? option.label : "";
    },
    /** 查询可投诉的订单列表 */
    getList() {
      this.loading = true;
      // 为了能够投诉，需要查询和当前用户相关的订单
      // 后端应该根据当前登录用户的ID，返回他作为"创建人"、"售前"、"售中"、"售后"或"技术员"的订单
      const params = {
        ...this.queryParams,
        userId: this.userId, // 传递当前用户ID
        queryForComplaint: true // 添加一个标志，告诉后端这是用于投诉的查询
      };
      listOrders(params).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 获取我的投诉历史 */
    getComplaintHistory() {
      this.complaintLoading = true;
      listComplaint(this.complaintQueryParams).then(response => {
        this.complaintHistoryList = response.rows;
        this.complaintTotal = response.total;
        this.complaintLoading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 投诉历史搜索按钮操作 */
    handleComplaintHistoryQuery() {
      this.complaintQueryParams.pageNum = 1;
      this.getComplaintHistory();
    },

    /** 投诉历史重置按钮操作 */
    resetComplaintHistoryQuery() {
      this.resetForm("complaintQueryForm");
      this.handleComplaintHistoryQuery();
    },

    /** 查看详情按钮操作 */
    handleViewContent(row) {
      this.contentViewOpen = true;
      this.currentContentView = row.content;
    },

    /** 查看解决方案详情按钮操作 */
    handleViewSolution(row) {
      this.contentViewTitle = "解决方案详情";
      this.currentContentView = row.solution;
      this.contentViewOpen = true;
    },

    /** "我要投诉"按钮操作 */
    handleComplaint(row) {
      this.resetComplaintForm();
      this.selectedOrder = row;

      // 填充表单
      this.complaintForm.orderId = row.id;
      this.complaintForm.orderNo = row.orderNo;
      this.complaintForm.userId = this.userId;
      this.complaintForm.userName = this.name;
      this.complaintForm.userLxfs = this.phonenumber; // 预填用户在系统的联系方式
      this.complaintForm.userContact = this.phonenumber; // 默认使用系统联系方式

      this.complaintOpen = true;
      this.complaintTitle = `对订单【${row.orderNo}】发起投诉`;
    },

    /** 当选择被投诉职位时，更新被投诉人/事选项 */
    handlePositionChange(selectedPositions) {
      if (!this.selectedOrder) return;

      const newTargetOptions = [];

      if (selectedPositions.includes('售前')) {
        const name = this.selectedOrder.preSaleName || '售前客服';
        const id = this.selectedOrder.preSaleId;
        newTargetOptions.push({
          name,
          id,
          position: '售前'
        });
      }
      if (selectedPositions.includes('售中')) {
        if (this.selectedOrder.inSaleName) {
          newTargetOptions.push({
            name: this.selectedOrder.inSaleName,
            id: this.selectedOrder.inSaleId,
            position: '售中'
          });
        }
      }
      if (selectedPositions.includes('售后')) {
        if (this.selectedOrder.afterSaleName) {
          newTargetOptions.push({
            name: this.selectedOrder.afterSaleName,
            id: this.selectedOrder.afterSaleId,
            position: '售后'
          });
        }
      }
      if (selectedPositions.includes('技术')) {
        if (this.selectedOrder.acceptedProgrammerName) {
          const names = String(this.selectedOrder.acceptedProgrammerName).split(',');
          const ids = this.selectedOrder.acceptedProgrammerId ? String(this.selectedOrder.acceptedProgrammerId).split(',') : [];
          names.forEach((name, index) => {
            if (name.trim()) {
              newTargetOptions.push({
                name: name.trim(),
                id: ids[index] ? ids[index].trim() : null,
                position: '技术'
              });
            }
          });
        }
      }

      this.targetOptions = newTargetOptions;
      const availableNames = newTargetOptions.map(opt => opt.name);
      if (this.complaintForm.selectedTargetNames) {
        this.complaintForm.selectedTargetNames = this.complaintForm.selectedTargetNames.filter(name => availableNames.includes(name));
      } else {
        this.$set(this.complaintForm, 'selectedTargetNames', []);
      }
    },

    /** 提交投诉按钮 */
    submitComplaintForm() {
      this.$refs["complaintForm"].validate(valid => {
        if (valid) {
          const payload = { ...this.complaintForm
          };

          const selectedTargets = this.targetOptions.filter(opt => payload.selectedTargetNames.includes(opt.name));

          payload.position = [...new Set(selectedTargets.map(t => t.position))].join(',');
          payload.positionName = selectedTargets.map(t => t.name).join(',');
          payload.positionId = selectedTargets.map(t => t.id).filter(id => id != null).join(',');

          delete payload.selectedTargetNames;

          if (payload.content) {
            payload.content = encodeURIComponent(payload.content);
          }
          addComplaint(payload).then(response => {
            this.$modal.msgSuccess("投诉提交成功，请等待处理");
            this.complaintOpen = false;
            // 如果当前就在历史列表，则刷新
            if (this.activeName === 'second') {
              this.getComplaintHistory();
            }
          });
        }
      });
    },

    /** 取消投诉按钮 */
    cancelComplaint() {
      this.complaintOpen = false;
      this.resetComplaintForm();
    },

    /** 重置投诉表单 */
    resetComplaintForm() {
      this.complaintForm = {
        orderId: null,
        orderNo: null,
        userId: null,
        userName: null,
        userLxfs: null, // 用户在系统的联系方式
        position: [],
        selectedTargetNames: [],
        content: null,
        userContact: null // 用户本次填写的联系方式
      };
      this.targetOptions = [];
      this.selectedOrder = null;
      if (this.$refs.complaintForm) {
        this.resetForm("complaintForm");
      }
    },

    /** Tab切换 */
    handleTabClick(tab, event) {
      if (tab.name === 'second' && !this.complaintHistoryList.length) {
        this.getComplaintHistory();
      }
    },
  }
};
</script>

<style scoped>
.complaint-content-view ::v-deep img {
  max-width: 100%;
  height: auto;
}

.file-list {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-list h4 {
  margin: 0 0 10px 0;
  color: #606266;
}

.file-list ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.file-list li {
  margin: 5px 0;
}

.file-list a {
  color: #409EFF;
  text-decoration: none;
}

.file-list a:hover {
  text-decoration: underline;
}

/* 居中对话框标题 */
.el-dialog__header {
  text-align: center;
}

/* 调整表单项间距和输入框字体 */
.el-form-item {
  margin-bottom: 20px;
  /* 增加底部间距 */
}

.el-input__inner,
.el-textarea__inner {
  font-size: 14px;
  /* 调整字体大小 */
}
</style>
